package com.sleepingcat.ft_flutter.channel

import com.sleepingcat.ft_flutter.pigeons.DialogBridge
import com.sleepingcat.lib_common.service.IFlutter
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.plugins.FlutterPlugin
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

class DialogChannel(engine: FlutterEngine) : FlutterPlugin, DialogBridge.DialogHostApi, CoroutineScope by MainScope() {

    val flutterApi by lazy { DialogBridge.DialogFlutterApi(engine.dartExecutor) }

    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        DialogBridge.DialogHostApi.setup(binding.binaryMessenger,this)
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        DialogBridge.DialogHostApi.setup(binding.binaryMessenger,null)
    }

    override fun showNativeNormalDialog(title: String, content: String, result: DialogBridge.Result<Boolean>) {
        launch {
            try {
                val ok = IFlutter.get()?.showNativeNormalDialog(title, content)
                result.success(ok)
            } catch (e: Exception) {
                result.error(e)
            }
        }
    }

    override fun showNativeInputDialog(title: String, content: String, hint: String, result: DialogBridge.Result<String>) {
        launch {
            try {
                val string = IFlutter.get()?.showNativeInputDialog(title, content, hint)
                result.success(string)
            } catch (e: Exception) {
                result.error(e)
            }
        }
    }


}